package com.gdk.ksoft.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.ui.logins.LoginActivity;
import com.gdk.ksoft.ui.mores.SoftwareSettingsActivity;
import com.gdk.ksoft.assembly.service.ForegroundService;
import com.gdk.ksoft.assembly.service.LocationService;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.ConfigUtils;
import com.gdk.ksoft.assembly.utils.system.PhoneUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 闪屏页面
 */
public class LogoActivity extends Activity {

    public static final int REQ_SETTING_ARGUMENTS = 0X00001;//请求设置参数的请求码

    @ViewInject(R.id.plogo_imgStartup)
    private ImageView imgStartup;//启动图，可以从网络上下载
    private ConfigUtils configUtils;//数据配置类
    private SharedPreferences sharedPreferences;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 0x001://改变图片的大小清晰度
                    //changeImageProperties();
                    break;
                case 0x002://请求用户连接URL地址
                    requestLoginUrl(LogoActivity.this);//请求用户连接URL地址
                    break;
            }
        }
    };

//    /**
//     * 修改图片属性
//     */
//    @TargetApi(11)
//    public void changeImageProperties(){
//        imgStartup.setAlpha((float)(imgStartup.getAlpha()*(1-0.2)));
//        imgStartup.setScaleX((float)(imgStartup.getScaleX()*(1+0.2)));
//        imgStartup.setScaleY((float)(imgStartup.getScaleY()*(1+0.2)));
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logo);
        configUtils = ConfigUtils.getInstance(this);
        ViewUtils.inject(this);
        startService(new Intent(this, ForegroundService.class));//启动后台进程服务
        startService(new Intent(this, LocationService.class));//启动地图定位服务

        sharedPreferences = configUtils.getSharedPreference();
        SystemData.UserPhone = PhoneUtils.getPhoneNumber(this);//获取手机号码
        try {
            SystemData.PhoneIMEI = PhoneUtils.getDeviceId(this);//获取手机标识
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("不能获取到设备的唯一标识符!");
        }
        if(TextUtils.isEmpty(SystemData.PhoneIMEI)){//获取手机唯一标识符失败
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LogoActivity.this,"该设备不支持获取串号信息!",Toast.LENGTH_SHORT).show();
                    LogoActivity.this.finish();//关闭该页面
                    return;
                }
            },1000);
            return;
        }
        //启动百度云推送
        PushManager.startWork(this, PushConstants.LOGIN_TYPE_API_KEY, ConstantData.BAIDU_PUSH_KEY);
        new Thread(){
            @Override
            public void run() {
                super.run();
                int count = 2;
                while(count >= 0){
                    handler.sendEmptyMessage(0x001);
                    count--;
                    try{Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}
                }
                handler.sendEmptyMessage(0x002);
            }
        }.start();
    }

    /**
     * 请求登录地址信息
     */
    public void requestLoginUrl(final Activity activity) {
        final ProgressDialog dialog = ProgressDialog.show(activity,"","正在初始化...");
        String methodName = "Cx_KeHuUrl";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
        RequestParams params = new RequestParams("UTF-8");
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        System.out.println("========请求用户连接的后台URL地址：" + MD5Utils.getMd5(methodName + messageBody + "19491001") + "=================");
        params.addBodyParameter("MessageBody",                                                                                                                                                                                                                                                                                                                                                                                                                                                                               "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}");
        new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT/3)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT / 2)
                .send(HttpRequest.HttpMethod.POST, ConstantData.UPDATE_URL+"/Mobile/CheXiao/", params, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> str) {
                                if (dialog != null && dialog.isShowing()) dialog.dismiss();
                                System.out.println("请求用户连接的后台URL地址结果是：----->" + str.result);
                                try {
                                    BaseResultModel resultModel = new Gson().fromJson(str.result, BaseResultModel.class);
                                    if (resultModel != null && (resultModel.Result.equals("0000"))) {
                                        if (resultModel.Result.equals("0000") && !TextUtils.isEmpty(resultModel.Data)) {
                                            String urlAction = resultModel.Data.replaceAll("\\\\", "/").replaceAll("(http|HTTP)://","").trim();//获取用户的URL地址,并保存至本地
                                            configUtils.getEditor().putString(SoftwareSettingsActivity.URL_ACTION,urlAction).commit();
                                            SystemData.BASE_URL = "http://" + urlAction +"/Mobile/CheXiao/";//设置公共访问端口路径
                                            gotoLoginPage();//跳转至登陆页
                                            return;
                                        }
                                    }
                                    showRetryDialog();//显示重试对话框
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                if (dialog != null && dialog.isShowing()) dialog.dismiss();
                                System.out.println("请求用户连接的后台URL地址结果是：----->"+s);
                                showNetworkErrorDialog();//显示网络错误的对话框
                            }
                        }
                );
    }

    /**
     * 连接地址是否可用
     * @return
     */
    public boolean isURLAvaliable(){
        String urlAction = configUtils.getSharedPreference().getString(SoftwareSettingsActivity.URL_ACTION, "");
        if(!TextUtils.isEmpty(urlAction)){
            SystemData.BASE_URL = "http://" + urlAction +"/Mobile/CheXiao/";
            return true;
        }
        return false;
    }

    /**
     * 跳转至登陆页
     */
    public void gotoLoginPage() {//启动登录页面
        Toast.makeText(this, "初始化完成!", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(LogoActivity.this, LoginActivity.class));
        LogoActivity.this.finish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 显示网络错误对话框
     */
    public void showNetworkErrorDialog(){
        if(!isURLAvaliable()) {//如果连接地址不可用，可能是网络原因造成的
            final MessageBox msgBox = new MessageBox(this);
            msgBox.setMessage("网络错误，请检查您的网络后重试！", "重试", "取消");
            msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    msgBox.dismiss();
                    switch (v.getId()) {
                        case MessageBox.ID_DIALOG_BUTTON_OK:
                            requestLoginUrl(LogoActivity.this);//重新请求连接地址信息
                            break;
                        case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                            LogoActivity.this.finish();
                            android.os.Process.killProcess(android.os.Process.myUid());
                            android.os.Process.killProcess(android.os.Process.myPid());
                            android.os.Process.killProcess(android.os.Process.myTid());
                            break;
                    }
                }
            });
            msgBox.show();
        }else{
            gotoLoginPage();//启动登录页面
        }
    }

    /**
     * 显示重试对话框
     */
    public void showRetryDialog(){
        String IMEI = "";
        try{
            IMEI = PhoneUtils.getDeviceId(this);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,"您的设备不支持获取串号信息!",Toast.LENGTH_SHORT).show();
            this.finish();
        }
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("本手机（手机串号" + IMEI + "）未注册，请到后台系统维护后重试！","重试","取消");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch (v.getId()) {
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        requestLoginUrl(LogoActivity.this);//重新请求连接地址信息
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        LogoActivity.this.finish();
                        android.os.Process.killProcess(android.os.Process.myUid());
                        android.os.Process.killProcess(android.os.Process.myPid());
                        android.os.Process.killProcess(android.os.Process.myTid());
                        break;
                }
            }
        });
        msgBox.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_SETTING_ARGUMENTS && resultCode == RESULT_OK) {
            gotoLoginPage();//跳转至登陆页
        }else{
            this.finish();
        }
    }
}
